import {
    doLogin,
    addUser,
    getUserList,
    deleteUser,
    getUserInfo,
    putUserInfo
  } from '@/api/contApi'
  
  import { setToken, delToken } from '@/utils/auth'
  import { setRole } from '@/utils/role'
  import { setMenu } from '@/utils/menu'
  
  export default {
    state: {
      username: '',
      token: '',
      uid: 0,
      role: '',
      menu: []
    },
    mutations: {
      // 设置token
      setToken(state, token) {
        setToken(token)
        state.token = token
      },
      // 登录成功后设置token值到vuex中
      addToken(state, data) {
        // 把token设置到本地存储中
        setToken(data.token)
        setRole(data.role)
        setMenu(data.menu)
  
        state.username = data.username
        state.token = data.token
        state.uid = data.uid
        state.role = data.role
        state.menu = data.menu
      },
      // 用户退出
      logout(state, data) {
        // 删除本地token值
        delToken()
        state.username = ''
        state.token = ''
        state.uid = 0
        state.role = ''
        state.menu = []
      }
    },
    actions: {
      // promise
      async loginAction({ commit }, { username, password }) {
        let ret = await doLogin(username, password)
        // 登录成功让token存储到vuex中和storage中
        ret.code === 0 && commit('addToken', ret.data)
        return ret.code === 0 ? true : false
      },
      // 添加用户
      async addUserAction({ commit }, userinfo) {
        let ret = await addUser(userinfo)
        return ret.code === 0 ? true : false
      },
      // 获取用户数据
      async getUserList({ commit }, page = 1) {
        return await getUserList(page)
      },
      //删除用户数据
      async deleteUserAction({ commit }, id) {
        return await deleteUser(id)
      },
      // 根据用户id获取用户数据
      async getUserInfoAction({ commit }, id) {
        return await getUserInfo(id)
      },
      // 修改用户
      async putUserInfoAction({ commit }, id) {
        return await putUserInfo(id)
      },
    }
  }